var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
var bodyParser = require('body-parser')
var Interceptor = require('./libs/interceptor')
var compression = require('compression')

var usersRouter = require('./routes/users')
var rolesRouter = require('./routes/roles')
var votesRouter = require('./routes/votes')
var optionsRouter = require('./routes/options')
var ballotsRouter = require('./routes/ballots')
var homeRouter = require('./routes/home')

var app = express()
// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(compression())
app.use(express.json())
app.use(
  express.urlencoded({
    extended: false
  })
)
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// 使用 body parser 将post参数及URL参数可以通过 req.body 拿到
app.use(
  bodyParser.urlencoded({
    extended: true
  })
)
app.use(bodyParser.json())
// 允许跨域访问
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  // 不设置客户端请求不能带自定义的该header：x-access-token
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,X-Access-Token')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  if (req.method !== 'OPTIONS') {
    let interceptor = new Interceptor(req)
    let authRes = interceptor.auth()
    if (authRes.code !== 0) {
      return res.status(authRes.code).json(authRes)
    } else {
      req.decoded = authRes.authDecoded
    }
  }
  next()
})

app.use('/api/users', usersRouter)
app.use('/api/roles', rolesRouter)
app.use('/api/votes', votesRouter)
app.use('/api/options', optionsRouter)
app.use('/api/ballots', ballotsRouter)
app.use('/api/home', homeRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404))
})

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render('error')
})

// 追加超时定义，避免检查大景点时超时
app.use(function(req, res, next) {
  res.setTimeout(1000 * 60 * 5, function() {
    // call back function is called when request timed out.
  })
  next()
})
module.exports = app
